<?php
/**
 * oppo rom 发布系统
 *
 * @author qianyunlai.com
 */

if(!defined('IN_DISCUZ')) {
	exit('Access Denied');
}

$theurl = 'oppo.php?mod=permission';
$btnValue = '添 加';

// 删除用户
if (isset($_GET['act']) && ($_GET['act'] == 'del')) {
	C::t('oppo_permission')->del_by_uid($_GET['uid']);
	dheader('Location:' . $theurl);
	die();
}

// 编辑用户
$userName = '';
$currProductIdArr = $currLevelIdArr = array();
if (isset($_GET['act']) && ($_GET['act'] == 'edit')) {
	$btnValue = '编 辑';
	$uid = intval($_GET['uid']);
	$userName = $_GET['username'];
	$permissionInfo = C::t('oppo_permission')->fetch_by_uid($uid);
	$currProductIdArr = explode(',', $permissionInfo['product_ids']);
	$currLevelIdArr = explode(',', $permissionInfo['level_ids']);
}

// 添加用户
if (isset($_POST['permissionsubmit']) && ($_POST['permissionsubmit'] == true)) {

	// 非空检测
	if (empty($_POST['user_name'])) {
		showmessage('用户名不能为空');
	}

	if (empty($_POST['product_id'])) {
		showmessage('请选择机型');
	}

	if (empty($_POST['level_id'])) {
		showmessage('请发布级别');
	}

	// 检测用户是否存在
	$userInfo = C::t('common_member')->fetch_by_username($_POST['user_name']);
	if (!$userInfo) {
		showmessage('此用户不存在');
	}
	$oldPermissionInfo = C::t('oppo_permission')->fetch_by_uid($userInfo['uid']);
	$data = array(
			'uid' => $userInfo['uid'],
			'user_name' => $userInfo['username'],
			'product_ids' => implode(',', $_POST['product_id']),
			'level_ids' => implode(',', $_POST['level_id']),
			'update_time' => $_G['timestamp']
	);
	if ($oldPermissionInfo) { // 更新
		C::t('oppo_permission')->update_by_uid($userInfo['uid'], $data);
	} else { // 添加
		$data['add_time'] = $_G['timestamp'];
		C::t('oppo_permission')->insert($data, 1);
	}
}

$productList = C::t('oppo_product')->fetch_all(1);
$permissionList = C::t('oppo_permission')->fetch_all();
$list = array();
foreach ($permissionList as $value) {
	$productIdArr = explode(',', $value['product_ids']);
	$levelIdArr = explode(',', $value['level_ids']);

	foreach ($productIdArr as $productId) {
		$value['products'] .= '，' . $productList[$productId]['product_name'];
	}
	$value['products'] = trim($value['products'], '，');

	foreach ($levelIdArr as $levelId) {
		$value['levels'] .= '，' . $publishLevel[$levelId];
	}
	$value['levels'] = trim($value['levels'], '，');

	$list[] = $value;
}

include template('oppo/oppo_permission');
?>